import getpass
import json
from pathlib import Path

def load_key(keyname: str) -> object:
    # 使用 pathlib 定位 resources 目录下的文件
    project_root = Path(__file__).parent.parent.parent
    # print("project_root: %s" % project_root)
    resources_dir = project_root / 'resources'
    file_name = resources_dir / 'Keys.json'

    # 确保 resources 目录存在
    resources_dir.mkdir(exist_ok=True)

    if file_name.exists():
        with open(file_name, "r") as f:
            key_data = json.load(f)
        if keyname in key_data and key_data[keyname]:
            return key_data[keyname]
        else:
            key_val = getpass.getpass("配置文件中没有相应键，请输入对应的配置信息: ").strip()
            key_data[keyname] = key_val
            with open(file_name, "w") as f:
                json.dump(key_data, f, indent=4)
            return key_val
    else:
        key_val = getpass.getpass("配置文件中没有相应键，请输入对应的配置信息: ").strip()
        key_data = {
            keyname: key_val
        }
        with open(file_name, "w") as f:
            json.dump(key_data, f, indent=4)
        return key_val

if __name__ == '__main__':
    # deepseek: sk-b89a47a6ee774ef2ba4940725a08dc14
    # print(load_key("LANGSMITH_API_KEY"))
    print(load_key("DEEPSEEK_API_KEY"))
